package com.css.util;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;


/**
 * @ClassName ServletUtil
 * @Auther qiumengmeng
 * @Date 2024/7/11 上午12:22
 */

public class ServletUtil extends cn.hutool.extra.servlet.ServletUtil {
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    public static JSONObject getParameter() {
        Map<String, String> paramMap   = getParamMap(getRequest());
        JSONObject jsonObject = null;
        if (CollUtil.isNotEmpty(paramMap)) {
            Map<String, String[]> params = getParams(getRequest());
            JSONObject jsonObjectTemp = new JSONObject();
            params.forEach((k, v) -> {
                jsonObjectTemp.put(k, v.length > 1 ? v : v[0]);
            });
            jsonObject = new JSONObject(jsonObjectTemp);
        } else {
            try {
                String body = getBody(getRequest());
                jsonObject = JSON.parseObject(body);
            } catch (Exception ignored) {
            }
        }
        return jsonObject;
    }
    public static String getClientIP() {
        return getClientIP(getRequest());
    }

    public static String getUri() {
        return getRequest().getRequestURI();
    }

    public static String getMethod() {
        return getRequest().getMethod();
    }

    public static String getUrl() {
        return getRequest().getRequestURL().toString();
    }
}

